<?php

namespace app\client\controller;

use think\Db;
use think\Config;
use think\Request;
use think\Session;
use think\Controller;
use app\client\model\ShopSpecAttr;
use app\client\model\ShopGoodsCombo as Combo;
use app\client\model\ShopGoods as ShopGoodsModel;
use app\common\trilateral\Classify as ClassifyAlias;
use app\client\model\ShopGoodsType as ShopGoodsTypeModel;
use app\client\model\ShopGoodsComboSelected as ShopGoodsComboSelectedModel;

class ShopGoodsCombo extends Controller
{

    /**
     * 商品套餐列表
     * @param Request $request
     * @param ShopGoodsComboSelectedModel $shopGoodsComboSelected
     * @return mixed
     */
    public function index(Request $request, ShopGoodsComboSelectedModel $shopGoodsComboSelected)
    {
        $title = ($request->instance()->has('title', 'get')) ? $request->instance()->get('title') : '';
        //查询套餐
        $Combo_Arr = (new Combo)->where('shop_id', Session::get('shop_id'))->where('title', 'like', '%' . $title . '%')->paginate(5, false, ['query' => ['title' => $title]]);

        //查询套餐商品
        $goods_Arr = [];
        if (!empty($Combo_Arr)) {

            $opt = [];
            foreach ($Combo_Arr as $v) {
                $opt[] = $v['id'];
            }
            $str = implode(',', $opt);
            // $goods_Arr = Db::view(['sun_shop_goods_combo_selected' => 'cs'], "id as cs_id,combo_id,sort,goods_attr_id")
            //     ->view(['sun_shop_goods' => 'sg'], 'id,title,price,market_price,freight', 'cs.goods_id = sg.id')
            //     ->where('cs.combo_id', 'in', $str)
            //     ->select();
            $ini['combo_id'] = ['in', $str];
            $goods_Arr = $shopGoodsComboSelected->with('shopGoods')->where($ini)->select();

            foreach ($goods_Arr as $k => &$v) {
                $v['attribute'] = ($v['goods_attr_id'] != 0) ? Db::name('ShopSpecAttr')->where('id', $v['goods_attr_id'])->value('attribute') : '无属性';
            }

        }
        // halt($Combo_Arr);
        // halt($goods_Arr);
        return $this->fetch('', [
            'mate_title' => '商品套餐列表',
            'combo_list' => $Combo_Arr,
            'goods_list' => $goods_Arr,
        ]);
    }


    /**
     * 删除套餐的商品
     * @param Request $request
     * @param Combo $combo
     * @return bool|int
     */
    public function destroy(Request $request, Combo $combo)
    {
        if ($request->instance()->isPost()) {
            if ($request->instance()->has('combo_id')) {   //套餐
                $combo_id = $request->instance()->post('combo_id');
                $page = $request->instance()->post('page');
                //删除套餐表中的套餐
                $res = $combo->destroy($combo_id);
                $num = $combo->count('id');
                $totalPage = ceil($num / 5);
                $nowPage = ($totalPage < $page) ? $totalPage : $page;
                //查出套餐所有关联的商品进行删除
                $goods_arr = Db::name('shopGoodsComboSelected')->where('combo_id', 'in', $combo_id)->column('id');
                $goods_str = empty($goods_arr) ?: implode(',', $goods_arr);
                //删除表中对应套餐的商品
                Db::name('shopGoodsComboSelected')->delete($goods_str);
                return $res ? (int)$nowPage : false;
            }
        }
    }

    /*
     * 审核启用或停用
     */
    public function auditing()
    {
        if (Request::instance()->isPost()) {
            if (Request::instance()->has('combo_id', 'post')) {  //父类状态变更
                $combo_id = Request::instance()->post('combo_id');
                $Combo = new Combo();
                $status = $Combo->where('id', $combo_id)->value('status');
                $update['status'] = ($status == 1) ? 0 : 1;
                $result = $Combo->where('id', $combo_id)->update($update);
                return $result ? true : false;
            }
        }
    }

    /*
     * 套餐添加
     */
    public function create()
    {
        // 读取店铺分类店铺商品
        $shopClassify = ShopGoodsTypeModel::where(['member_id' => Session::get('shop_id')])->field('id,title,parenTid,parentStr,count')->select()->toArray();
        return $this->fetch('', [
            'mate_title'   => '商品套餐添加',
            'shopClassify' => ClassifyAlias::dimension($shopClassify),
        ]);
    }

    /*
     * 商品联动
     */
    public function linkage()
    {
        if (Request::instance()->isPost()) {
            //动态更改配置
            Config::set('default_ajax_return', 'html');
            //商品联动
            $data = Request::instance()->post();
            $idStr = $this->type_all($data['type_id']);
            //查找商品
            $goods_Arr = ShopGoodsModel::where('parenTid', 'in', $idStr)
                ->where('member_id', Session::get('shop_id'))
                ->where(['state' => 1])
                ->field('id,title')
                ->order("create_time desc")
                ->select();
            $opt = '';
            foreach ($goods_Arr as $v) {
                $opt .= "<option value='" . $v['id'] . "' class='shop_goods_" . $v['id'] . "'>" . $v['title'] . "</option>";
            }
            return "<select class='form-control' id='ManySelect' onchange='check()'><option disabled selected>请选择商品(含" . count($goods_Arr) . "种商品)</option>" . $opt . "</select>";
        }
    }

    /*
     * 二级分类下的所有分支id
     */
    public function type_all($id)
    {
        $Arr = ShopGoodsTypeModel::where(['status' => 1])->field(['id', 'parentStr'])->select();
        $opt = [];
        foreach ($Arr as $v) {
            if (in_array($id, explode(',', $v['parentStr']))) {
                $opt[] = $v['id'];
            }
        }
        return empty($opt) ? $id : $id . ',' . implode(',', $opt);
    }

    /*
     * 罗列套餐商品
     */
    public function set_out()
    {
        if (Request::instance()->isPost()) {
            //动态更改配置
            Config::set('default_ajax_return', 'html');
            $default = "<tr id='Default'><td colspan='8'><div style='font-size:24px;margin:30px 0;'>未选择商品</div></td></tr>";
            if (empty(Request::instance()->post('id/a'))) {
                return $default;
            };
            $id = Request::instance()->post('id');

            //查询对应的商品
            $data = (new ShopGoodsModel())->where('id', $id)
                ->with('shopSpecAttr')
                ->field(['id,goods_title', 'title', 'price', 'market_price', 'freight'])
                ->find();
            $spec = Db::name('shopSpecAttr')->where('goods_id',$id)->count();

            if ($spec == 0) {

                $opt_noAttr = '<tr class="select_goods" id="tr_' . $data['id'] . '"><td align="center"><span class="sort"></span><input type="hidden" class="ids" name="goods_id[]" value="' . $data['id'] . '" /></td><td><span>' . $data['goods_title'] . '</span></td><td><span>' . $data['title'] . '</span></td><td><input type="hidden" name="attr[]" value="0" /><span class="showAttr_' . $data['id'] . '">无属性</span></td><td><span class="old_price">' . $data['price'] . '</span></td><td><span class="market_price">' . $data['market_price'] . '</span></td><td><span class="freight_price">' . $data['freight'] . '</span></td><td><span><a href="javascript:remove(' . $data['id'] . ');" class="label label-danger"><span class="fa fa-times"></span>&nbsp;&nbsp;移 除</a></span>&nbsp;&nbsp;&nbsp;&nbsp;<span><a  id="modal-680565" role="button" data-toggle="modal" class="label" style="background-color:gray"><span class="fa fa-toggle-down (alias)"></span>&nbsp;&nbsp;属 性</a></span>&nbsp;&nbsp;&nbsp;&nbsp;<span><a href="javascript:move(' . $data['id'] . ');" class="label label-danger"><span class="fa fa-arrows"></span>&nbsp;&nbsp;下 移</a></span></td></tr>';
                return $opt_noAttr;
            }else{
                $first_Attr = $data->shopSpecAttr[0]['attribute'];
                $attr_id = $data->shopSpecAttr[0]['id'];
                $opt = '<tr class="select_goods" id="tr_' . $data['id'] . '"><td align="center"><span class="sort"></span><input type="hidden" class="ids" name="goods_id[]" value="' . $data['id'] . '" /></td><td><span>' . $data['goods_title'] . '</span></td><td><span>' . $data['title'] . '</span></td><td><input type="hidden" name="attr[]" value="' . $attr_id . '" /><span class="showAttr_' . $data['id'] . '">' . $first_Attr . '</span></td><td><span class="old_price">' . $data['price'] . '</span></td><td><span class="market_price">' . $data['market_price'] . '</span></td><td><span class="freight_price">' . $data['freight'] . '</span></td><td><span><a href="javascript:remove(' . $data['id'] . ');" class="label label-danger"><span class="fa fa-times"></span>&nbsp;&nbsp;移 除</a></span>&nbsp;&nbsp;&nbsp;&nbsp;<span><a  id="modal-680565" href="#modal-container-680565" onclick="dialog(' . $data['id'] . ')" role="button" data-toggle="modal" class="label label-danger"><span class="fa fa-toggle-down (alias)"></span>&nbsp;&nbsp;属 性</a></span>&nbsp;&nbsp;&nbsp;&nbsp;<span><a href="javascript:move(' . $data['id'] . ');" class="label label-danger"><span class="fa fa-arrows"></span>&nbsp;&nbsp;下 移</a></span></td></tr>';
                return $opt;
            }


        }
    }

    /*
     * 属性选择
     */
    public function attr_select()
    {
        Config::set('default_ajax_return', 'html');
        if (Request::instance()->isPost()) {
            $id = Request::instance()->post('id');
            //查询此商品的属性
            $attr = (new ShopGoodsModel())->where('id', $id)
                ->value('goods_attr');
            $attr = unserialize($attr);
            $each = '';
            $num = 0;
            foreach ($attr as $k => $v) {
                $head = "<div>" . $k;
                $content = '';
                foreach ($v as $vv) {
                    $content .= "<li onclick='select_attr(this)' class='attr_" . $num . " goods_attr' style='float: left;margin-right:10px;padding: 0 8px;list-style-type:none;cursor: pointer;'>" . $vv . "</li>";
                }
                $each .= $head . "<ul>" . $content . "</ul></div><br/>";
                $num++;
            }
            $default = "<input type='hidden' id='selected_id' value='" . $id . "' />";
            return $each . $default;
        }
    }

    /*
     * 确定新的属性
     */
    public function new_attr()
    {
        if (Request::instance()->isPost()) {
            $id = Request::instance()->post('id');
            $attribute = Request::instance()->post('attribute');
            $find = (new ShopSpecAttr())->where(['goods_id' => $id, 'attribute' => $attribute])
                ->field(['id', 'market_price', 'price'])
                ->find();
            return empty($find) ? ['message' => '数据库中未找到此类属性组合', 'id' => 0] : $find;
        }
    }

    /*
     * 创建套餐
     */
    public function create_combo()
    {
        if (Request::instance()->isPost()) {
            $data = Request::instance()->post();
            list($begin, $end) = explode('/', $data['interval_timer']);
            $data['begin_time'] = strtotime($begin);
            $data['end_time'] = strtotime($end);
            $model = new Combo();
            $res = $model->isUpdate(false)->allowField(true)->save($data);
            $map = [];
            foreach ($data['goods_id'] as $k => $v) {
                $map[$k]['combo_id'] = $model->id;
                $map[$k]['goods_id'] = $v;
                $map[$k]['sort'] = $k + 1;
                $map[$k]['goods_attr_id'] = $data['attr'][$k];
            }
            $selected_res = (new ShopGoodsComboSelectedModel())->isUpdate(false)->saveAll($map);
            $res && $selected_res ? win('提交成功', url('client/shopGoodsCombo/index')) : fail('提交失败');
        }
    }

    /*
     * 编辑套餐展示页
     */
    public function update($id, $search = '', $page = '')
    {

        $model = new ShopGoodsComboSelectedModel();
        if (Request::instance()->isGet()) {
            //套餐和选中的商品一对多
            $data = Combo::get($id, 'shopGoodsComboSelected');
            $selectId = [];
            foreach ($data->shopGoodsComboSelected as $v) {
                $selectId[] = $v['id'];
            }

            //选中的商品和属性多对一
            $specArr = $model->where('id', 'in', implode(',', $selectId))->relation('shopSpecAttr')->select();
            //选中的商品和商品表多对一
            $goodsArr = $model->where('id', 'in', implode(',', $selectId))->relation('shopGoods')->select();

            $opt = '';
            //组装选中的商品列表
            foreach ($specArr as $k => $v) {
                //判断是否为无属性商品并进行改造
                if (is_null($v->shopSpecAttr)) {
                    $opt .= '<tr class="select_goods" id="tr_' . $v['goods_id'] . '"><td align="center"><span class="sort"></span><input type="hidden" class="ids" name="goods_id[]" value="' . $v['goods_id'] . '" /></td><td><span>' . $goodsArr[$k]->shopGoods['goods_title'] . '</span></td><td><span>' . $goodsArr[$k]->shopGoods['title'] . '</span></td><td><input type="hidden" name="attr[]" value="0" /><span class="showAttr_' . $v['goods_id'] . '">无属性</span></td><td><span class="old_price">' . $goodsArr[$k]->shopGoods['price'] . '</span></td><td><span class="market_price">' . $goodsArr[$k]->shopGoods['market_price'] . '</span></td><td><span class="freight_price">' . $goodsArr[$k]->shopGoods['freight'] . '</span></td><td><span><a href="javascript:remove(' . $v['goods_id'] . ');" class="label label-danger"><span class="fa fa-times"></span>&nbsp;&nbsp;移 除</a></span>&nbsp;&nbsp;&nbsp;&nbsp;<span><a  id="modal-680565" role="button" data-toggle="modal" class="label" style="background-color:gray"><span class="fa fa-toggle-down (alias)"></span>&nbsp;&nbsp;属 性</a></span>&nbsp;&nbsp;&nbsp;&nbsp;<span><a href="javascript:move(' . $v['goods_id'] . ');" class="label label-danger"><span class="fa fa-arrows"></span>&nbsp;&nbsp;下 移</a></span></td></tr>';

                } else {
                    $opt .= '<tr class="select_goods" id="tr_' . $v['goods_id'] . '"><td align="center"><span class="sort"></span><input type="hidden" class="ids" name="goods_id[]" value="' . $v['goods_id'] . '" /></td><td><span>' . $goodsArr[$k]->shopGoods['goods_title'] . '</span></td><td><span>' . $goodsArr[$k]->shopGoods['title'] . '</span></td><td><input type="hidden" name="attr[]" value="' . $v['goods_attr_id'] . '" /><span class="showAttr_' . $v['goods_id'] . '">' . $v->shopSpecAttr['attribute'] . '</span></td><td><span class="old_price">' . $v->shopSpecAttr['price'] . '</span></td><td><span class="market_price">' . $v->shopSpecAttr['market_price'] . '</span></td><td><span class="freight_price">' . $goodsArr[$k]->shopGoods['freight'] . '</span></td><td><span><a href="javascript:remove(' . $v['goods_id'] . ');" class="label label-danger"><span class="fa fa-times"></span>&nbsp;&nbsp;移 除</a></span>&nbsp;&nbsp;&nbsp;&nbsp;<span><a  id="modal-680565" href="#modal-container-680565" onclick="dialog(' . $v['goods_id'] . ')" role="button" data-toggle="modal" class="label label-danger"><span class="fa fa-toggle-down (alias)"></span>&nbsp;&nbsp;属 性</a></span>&nbsp;&nbsp;&nbsp;&nbsp;<span><a href="javascript:move(' . $v['goods_id'] . ');" class="label label-danger"><span class="fa fa-arrows"></span>&nbsp;&nbsp;下 移</a></span></td></tr>';
                }
            }

            $data['list'] = $opt;
            $data['page'] = $page;
            $data['search'] = $search;
            $shopClassify = ShopGoodsTypeModel::where(['member_id' => Session::get('shop_id')])->field('id,title,parenTid,parentStr,count')->select()->toArray();


            return $this->fetch('', [
                'mate_title'   => '商品套餐编辑',
                'editArr'      => $data,
                'shopClassify' => ClassifyAlias::dimension($shopClassify),
            ]);
        }
    }

    /*
     * 编辑套餐处理
     */
    public function update_act()
    {
        if (Request::instance()->isPost()) {
            $data = Request::instance()->post();
            //销毁套餐原选定商品
            $res = (new ShopGoodsComboSelectedModel())->where('combo_id', $data['combo_id'])->delete();
            if ($res) {
                list($begin, $end) = explode('/', $data['interval_timer']);
                $data['begin_time'] = strtotime($begin);
                $data['end_time'] = strtotime($end);
                $combo_res = (new Combo())->allowField(true)->isUpdate(true)->save($data);
                if ($combo_res || $combo_res === 0) {
                    $map = [];
                    foreach ($data['goods_id'] as $k => $v) {
                        $map[$k]['combo_id'] = $data['combo_id'];
                        $map[$k]['goods_id'] = $v;
                        $map[$k]['sort'] = $k + 1;
                        $map[$k]['goods_attr_id'] = $data['attr'][$k];
                    }
                    $selected_res = (new ShopGoodsComboSelectedModel())->isUpdate(false)->saveAll($map);
                    $selected_res ? win('提交成功', url("client/shopGoodsCombo/index") . '?title=' . $data['search'] . '&page=' . $data['page']) : fail('提交失败');
                }
            }
        }
    }
}